package org.example.web;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageInfo;
import org.example.entity.Emp;
import org.example.entity.Role;
import org.example.pojo.Result;
import org.example.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private HttpSession session;

    @GetMapping("/list")
    public Result<List<Role>> list(Integer page,Integer limit,String searchRoleName){
        PageInfo<Role> pageInfo = roleService.listByPage(page, limit, searchRoleName);
        return Result.success(pageInfo.getList(),pageInfo.getTotal());
    }
    //新增员工时下拉框所需的数据
    @GetMapping("/listAll")
    public Result listAll(){
        List<Role> roleList = roleService.list();
        return Result.success(roleList,roleList.size());
    }

    @PostMapping("/add")
    public Result add(Role role){
        Emp emp = (Emp) session.getAttribute("empSession");

        role.setCreateBy(emp.getEmpName());
        role.setCreateTime(new Date());
        boolean saveResult = roleService.save(role);
        if(saveResult){
            return new Result(0,"保存成功",1,true);
        }else{
            return Result.fail("保存失败");
        }
    }
    @PostMapping("/update")
    public Result update(Role role){
        Emp empSession = (Emp) session.getAttribute("empSession");
        role.setUpdateBy(empSession.getEmpName());
        role.setUpdateTime(new Date());
        boolean updateResult = roleService.updateById(role);
        if(updateResult){
            return new Result(0,"编辑成功",1,true);
        }else{
            return Result.fail("编辑失败");
        }

    }

    @DeleteMapping("/delete")
    public Result delete(Role role){
        //逻辑删除
        Emp empSession = (Emp) session.getAttribute("empSession");
        LambdaUpdateWrapper<Role> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(Role::getRoleId,role.getRoleId());
        lambdaUpdateWrapper.set(Role::getDeleteFlag,1);
        lambdaUpdateWrapper.set(Role::getUpdateBy,empSession.getEmpName());
        lambdaUpdateWrapper.set(Role::getUpdateTime,new Date());
        boolean removeResult = roleService.update(lambdaUpdateWrapper);
        if(removeResult){
            return new Result<>(0,"删除成功",1,true);
        }else{
            return Result.fail("删除失败");
        }
    }
}
